<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,200分)- 污染水域（Java & JS & Python & C）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>输入一行字符串&#xff0c;字符串可转换为N*N的数组&#xff0c;数组可认为是一个水域&#xff0c;判断多少天后&#xff0c;水域被全部污染。<br /> 数组中只有0和1&#xff0c;0表示纯净&#xff0c;1表示污染&#xff0c;每天只可污染上下左右的水域&#xff0c;如果开始全部被污染&#xff0c;或永远无法污染&#xff0c;则返回-1。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>无</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>无</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">1,0,1,0,0,0,1,0,1</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">2</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;"> <p>输入转化为数组为&#xff1a;<br /> 1 0 1<br /> 0 0 0<br /> 1 0 1</p> <p>第一天后水域变为</p> <p><code>1 1 1</code><br /><code>1 0 1</code><br /><code>1 1 1</code></p> <p>第二天全部被污染</p> </td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">0,0,0,0</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">-1</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题可以采用图的多源BFS来解决。图的多源BFS实现关键点在于理解queue的作用。解析可以参考&#xff1a;<a href="https://fcqian.blog.csdn.net/article/details/127711317" rel="nofollow" title="华为OD机试 - 计算疫情扩散时间&#xff08;Java &amp; JS &amp; Python &amp; C&#xff09;_伏城之外的博客-CSDN博客">华为OD机试 - 计算疫情扩散时间&#xff08;Java &amp; JS &amp; Python &amp; C&#xff09;_伏城之外的博客-CSDN博客</a></p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  const nums &#61; line.split(&#34;,&#34;).map(Number);

  console.log(getResult(nums));
});

function getResult(nums) {
  // 矩阵 n x n
  const n &#61; Math.sqrt(nums.length);

  // 未污染区域数量
  let total &#61; nums.length;

  // 矩阵
  const matrix &#61; new Array(n).fill(0).map(() &#61;&gt; new Array(n));

  // BFS队列
  let queue &#61; [];

  for (let i &#61; 0; i &lt; n; i&#43;&#43;) {
    for (let j &#61; 0; j &lt; n; j&#43;&#43;) {
      matrix[i][j] &#61; nums[i * n &#43; j];

      if (matrix[i][j] &#61;&#61;&#61; 1) {
        queue.push([i, j]);
        total--;
      }
    }
  }

  if (queue.length &#61;&#61;&#61; 0 || queue.length &#61;&#61;&#61; nums.length) {
    return -1;
  }

  // 上下左右方位偏移量
  const offsets &#61; [
    [-1, 0],
    [1, 0],
    [0, -1],
    [0, 1],
  ];

  // 扩散天数
  let day &#61; 0;

  while (queue.length &gt; 0 &amp;&amp; total &gt; 0) {
    const newQueue &#61; [];

    for (const [i, j] of queue) {
      for (const [offsetI, offsetJ] of offsets) {
        const newI &#61; i &#43; offsetI;
        const newJ &#61; j &#43; offsetJ;

        if (
          newI &gt;&#61; 0 &amp;&amp;
          newI &lt; n &amp;&amp;
          newJ &gt;&#61; 0 &amp;&amp;
          newJ &lt; n &amp;&amp;
          matrix[newI][newJ] &#61;&#61; 0
        ) {
          matrix[newI][newJ] &#61; 1;
          newQueue.push([newI, newJ]);
          total--;
        }
      }
    }

    queue &#61; newQueue;
    day&#43;&#43;;
  }

  return day;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
  // 输入获取
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);
    int[] nums &#61; Arrays.stream(sc.nextLine().split(&#34;,&#34;)).mapToInt(Integer::parseInt).toArray();
    System.out.println(getResult(nums));
  }

  // 算法入口
  public static int getResult(int[] nums) {
    int n &#61; (int) Math.sqrt(nums.length);

    LinkedList&lt;int[]&gt; queue &#61; new LinkedList&lt;&gt;();
    int[][] matrix &#61; new int[n][n];
    int total &#61; nums.length;

    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      for (int j &#61; 0; j &lt; n; j&#43;&#43;) {
        matrix[i][j] &#61; nums[i * n &#43; j];

        if (matrix[i][j] &#61;&#61; 1) {
          queue.add(new int[] {i, j});
          total--;
        }
      }
    }

    if (queue.size() &#61;&#61; 0 || queue.size() &#61;&#61; nums.length) {
      return -1;
    }

    int day &#61; 0;

    int[][] offsets &#61; {<!-- -->{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    while (queue.size() &gt; 0 &amp;&amp; total &gt; 0) {
      LinkedList&lt;int[]&gt; newQueue &#61; new LinkedList&lt;&gt;();

      for (int[] pos : queue) {
        int i &#61; pos[0];
        int j &#61; pos[1];

        for (int[] offset : offsets) {
          int newI &#61; i &#43; offset[0];
          int newJ &#61; j &#43; offset[1];

          if (newI &gt;&#61; 0 &amp;&amp; newI &lt; n &amp;&amp; newJ &gt;&#61; 0 &amp;&amp; newJ &lt; n &amp;&amp; matrix[newI][newJ] &#61;&#61; 0) {
            matrix[newI][newJ] &#61; 1;
            newQueue.add(new int[] {newI, newJ});
            total--;
          }
        }
      }

      queue &#61; newQueue;
      day&#43;&#43;;
    }

    return day;
  }
}
</code></pre> 
<p></p> 
<h4 style="background-color:transparent;">Python算法源码</h4> 
<pre><code class="language-python">import math

# 输入获取
nums &#61; list(map(int, input().split(&#34;,&#34;)))


# 算法入口
def getResult():
    # 矩阵 n x n
    n &#61; int(math.sqrt(len(nums)))

    # 未污染区域数量
    total &#61; len(nums)

    # 矩阵
    matrix &#61; [[0 for _ in range(n)] for _ in range(n)]

    # BFS队列
    queue &#61; []

    for i in range(n):
        for j in range(n):
            matrix[i][j] &#61; nums[i * n &#43; j]
            if matrix[i][j] &#61;&#61; 1:
                queue.append([i, j])
                total -&#61; 1

    if len(queue) &#61;&#61; 0 or len(queue) &#61;&#61; len(nums):
        return -1

    # 上下左右偏移量
    offsets &#61; ((-1, 0), (1, 0), (0, -1), (0, 1))

    # 扩散天数
    day &#61; 0

    while len(queue) &gt; 0 and total &gt; 0:
        newQueue &#61; []

        for i, j in queue:
            for offsetX, offsetY in offsets:
                newI &#61; i &#43; offsetX
                newJ &#61; j &#43; offsetY

                if 0 &lt;&#61; newI &lt; n and 0 &lt;&#61; newJ &lt; n and matrix[newI][newJ] &#61;&#61; 0:
                    matrix[newI][newJ] &#61; 1
                    newQueue.append([newI, newJ])
                    total -&#61; 1

        queue &#61; newQueue
        day &#43;&#61; 1

    return day


# 算法调用
print(getResult())
</code></pre> 
<p></p> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;math.h&gt;

#define MAX_SIZE 1024

typedef struct ListNode {
    int ele;
    struct ListNode *next;
} ListNode;

typedef struct {
    int size;
    ListNode *head;
    ListNode *tail;
} LinkedList;

LinkedList *new_LinkedList();
void addLast_LinkedList(LinkedList *link, int ele);

int matrix[MAX_SIZE][MAX_SIZE] &#61; {0};
int nums[MAX_SIZE * MAX_SIZE];
int nums_size &#61; 0;

int getResult();

int main() {
    while(scanf(&#34;%d&#34;, &amp;nums[nums_size&#43;&#43;])) {
        if(getchar() !&#61; &#39;,&#39;) break;
    }

    printf(&#34;%d\n&#34;, getResult());

    return 0;
}

int getResult() {
    // 矩阵 n x n
    int n &#61; (int) sqrt(nums_size);

    // 未污染水域数量
    int total &#61; nums_size;

    // BFS队列
    LinkedList* queue &#61; new_LinkedList();

    for(int i&#61;0; i &lt; n; i&#43;&#43;) {
        for(int j &#61; 0; j &lt; n; j&#43;&#43;) {
            matrix[i][j] &#61; nums[i * n &#43; j];

            if(matrix[i][j] &#61;&#61; 1) {
                addLast_LinkedList(queue, i * n &#43; j);
                total--;
            }
        }
    }

    if(queue-&gt;size &#61;&#61; 0 || queue-&gt;size &#61;&#61; nums_size) {
        return -1;
    }

    // 上下左右偏移量
    int offsets[4][2] &#61; {<!-- -->{1,  0},
                         {-1, 0},
                         {0,  1},
                         {0,  -1}};

    // 扩散时间
    int day &#61; 0;

    // 如果扩散点没有了&#xff0c;或者所有点已被扩散&#xff0c;则停止循环
    while (queue-&gt;size &gt; 0 &amp;&amp; total &gt; 0) {
        LinkedList *newQueue &#61; new_LinkedList();

        ListNode *cur &#61; queue-&gt;head;
        while (cur !&#61; NULL) {
            int x &#61; cur-&gt;ele / n;
            int y &#61; cur-&gt;ele % n;

            for (int i &#61; 0; i &lt; 4; i&#43;&#43;) {
                int newX &#61; x &#43; offsets[i][0];
                int newY &#61; y &#43; offsets[i][1];

                if (newX &gt;&#61; 0 &amp;&amp; newX &lt; n &amp;&amp; newY &gt;&#61; 0 &amp;&amp; newY &lt; n &amp;&amp; matrix[newX][newY] &#61;&#61; 0) {
                    // 将点被扩散的时间记录为该点的值
                    matrix[newX][newY] &#61; 1;
                    // 被扩散到的点将变为新的扩散源
                    addLast_LinkedList(newQueue, newX * n &#43; newY);
                    // 未被扩散点的数量--
                    total--;
                }
            }
            cur &#61; cur-&gt;next;
        }

        queue &#61; newQueue;
        day&#43;&#43;;
    }

    return day;
}

LinkedList *new_LinkedList() {
    LinkedList *link &#61; (LinkedList *) malloc(sizeof(LinkedList));

    link-&gt;size &#61; 0;
    link-&gt;head &#61; NULL;
    link-&gt;tail &#61; NULL;

    return link;
}

void addLast_LinkedList(LinkedList *link, int ele) {
    ListNode *node &#61; (ListNode *) malloc(sizeof(ListNode));

    node-&gt;ele &#61; ele;
    node-&gt;next &#61; NULL;

    if (link-&gt;size &#61;&#61; 0) {
        link-&gt;head &#61; node;
        link-&gt;tail &#61; node;
    } else {
        link-&gt;tail-&gt;next &#61; node;
        link-&gt;tail &#61; node;
    }

    link-&gt;size&#43;&#43;;
}</code></pre> 
<p> </p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>